
### PackageManager Description Start ###
# 1,配合ChangeLog使用.
# 2,检查当前主工程的版本号.
# 3,编译打包到蒲公英
### VersionManager Description End  ###


### Input Start ###
# 所有的需要用户配置的信息
# 工程的info.plist文件路径
projectInfoPlistPath="/Users/gikkiares/Desktop/MP_MyProject/Mp01_SoftwareProject/Mp0106_MyLibProject/MP0601_iOS/JsUtilityDemo/JsUtilityDemo/JsUtilityDemo/Info.plist"
workspaceFilePath="/Users/gikkiares/Desktop/MP_MyProject/Mp01_SoftwareProject/Mp0106_MyLibProject/MP0601_iOS/JsUtilityDemo/JsUtilityDemo/JsoUtilitySdkDemo.xcworkspace"
pgyApiKey="d547a764af6e143b8021d29ec8f83c7f"
# changeLog文件路径.
changeLogPath="/Users/gikkiares/Desktop/MP_MyProject/Mp01_SoftwareProject/Mp0106_MyLibProject/MP0601_iOS/JsUtilityDemo/JsUtilityDemo/ReadMe/ChangeLog.md"
projectDirPath="/Users/gikkiares/Desktop/MP_MyProject/Mp01_SoftwareProject/Mp0106_MyLibProject/MP0601_iOS/JsUtilityDemo/JsUtilityDemo"

configuration="Release"
scheme="JsoUtilitySdkDemo"
targetName="JsoUtilitySdkDemo"

podspecPath="/Users/gikkiares/Desktop/MP_MyProject/Mp01_SoftwareProject/Mp0106_MyLibProject/MP0601_iOS/JsUtilityDemo/JsUtilityDemo/JsoUtilitySdk.podspec"


teamId="726NDCHRGU"
bundleId="com.vgemv.JsoUtilitySdkDemo"
### Input End  ###


### Variable Start ### 
#程序需要用到的变量
# Change log中指定的版本.
newVersion=""
newBuildNumber=""
# 改动点.
change=""
# plist文件中指定的版本
currentVersion=""
currentBuildNumber=""

# 上传结果
uploadResult=""

buildDir=""
outArchivePath=""
# 输出文件的目录
exportDirPath=""
plistFilePath=""
ipaPath=""

### Variable End ###


function main {

    # 1 读取版本信息

    ## 1.1 逐行处理ChangeLog.md文件
    ### 1.1.1 获取Version
    newVersion=$(awk 'BEGIN {currentTagIndex=0;version=""} {if($1 == "#"){currentTagIndex++; if(currentTagIndex==1){version=""$2;version2=substr(version,2,length(version)-2) ;exit}}} END{print version2}' ${changeLogPath})
    newBuildNumber=$(buildNumberForVersion ${newVersion})
    echo "New version is: ${newVersion},build number is: ${newBuildNumber}"

    ### 1.1.2 获取change
    change=$(awk 'BEGIN {currentTagIndex=0;comment="";} {if($1 == "#"){currentTagIndex++;}  if(currentTagIndex == 1) {comment = (comment""$0"\n")}else if(currentTagIndex>1){exit} } END{print comment}' ${changeLogPath})
    echo "New version change is :\n${change}"

    ## 1.2 获取项目当前版本信息
    currentVersion=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "${projectInfoPlistPath}")
    currentBuildNumber=$(buildNumberForVersion ${currentVersion})
    echo "Current version is: ${currentVersion},build number is: ${currentBuildNumber}"

    ## 1.3 比较,如果相同则
    if (( ${newBuildNumber} >= ${currentBuildNumber} )); then
        echo "Do you want to upgrade version from ${currentVersion} to ${version} Y/n?"
        read choice
        if [[ "${choice}" != "n" ]]; then
            # build目录
            buildDir="${workspaceFilePath}/../Build"
            buildDir_newVersion="${buildDir}/${newVersion}"
            # 归档文件
            outArchivePath="${buildDir_newVersion}/${targetName}.xcarchive"
            # 导出文件目录
            exportDirPath="${buildDir_newVersion}/export"
            plistFilePath="${buildDir}/export.plist"
            ipaPath="${exportDirPath}/${targetName}.ipa"

            upgradeVersion 
            checkPodGit

            latestTag=$(getPodGitLocalLatestTag)
            # 当前podversion
            curerntPodVersion=${getPodspecVersion}
            echo "The current version is: ${curerntPodVersion}"
            podVersionNumber=$(buildNumberForVersion ${curerntPodVersion})

            if (( ${newBuildNumber} >= ${podVersionNumber} )); then

                git tag ${newVersion}
                git push origin ${newVersion}
                latestTag=$(getPodGitLocalLatestTag)
                echo "The latest tag is: ${latestTag}"
                updatePodspec
                #成功则退出,否则回滚
                [[ $? == 0 ]] && echo "Pod spec update success" && exit 

                echo "Roll back"
                git tag -d ${newVersion}
                git push origin :refs/tags/${newVersion}
                latestTag=$(getPodGitLocalLatestTag)
                echo "The latest tag after roll back is: ${latestTag}"

            else 
                echo "The current version tag is used,please update your version."
            fi
        else
            exit
        fi
    else
        echo "New version is not above current version."
        exit
    fi
}

function buildNumberForVersion {
    version=$1
    array=(${version//./ })  
    # echo ${array[0]};
    # echo ${array[@]}
    declare -i i=2
    declare -i buildNumber=0
    for var in ${array[@]}
    do
        ((buildNumber += ${var} * 100 ** i)) 
        ((--i))
    done
    # echo "BuildNumber is: ${buildNumber}"
    echo ${buildNumber}
}

## 1.4 设置xcode版本
function upgradeVersion {
    version=${newVersion}
    buildNumber=${newBuildNumber}

    

    #  shortVersion为指定的版本号eg: 1.2.3
    /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString ${version}" "${projectInfoPlistPath}"
    # 设置build号.
    /usr/libexec/PlistBuddy -c "Set :CFBundleVersion ${buildNumber}" "${projectInfoPlistPath}"


    cd ${projectDirPath}
    #更新所有Target的${MARKETING_VERSION},用于设置short version
    xcrun agvtool new-marketing-version ${version}
    #更新${CURRENT_PROJECT_VERSION}用于设置build number
    xcrun agvtool new-version ${buildNumber}
}

# 检查PodGit,git
function checkPodGit {
        gitStatus=`git status -s`
        echo "Git status is ${gitStatus}"
        if [[ "${gitStatus}" == "" ]]; then
            echo "Git is clean..."
        else
            git add . 
            git commit -a -m "${change}"
            git push 
            echo "Git is not clean,please clean it with source tree"
        fi
}

function getPodGitLocalLatestTag2 {
    ret=`git tag -l`
    tagArray=(${ret/\n/})
    itemCount=${#tagArray[*]}
    # echo "${tagArray}"
    # echo "There are ${itemCount} items in the array"
    latestTag=${tagArray[${itemCount}-1]}
    # echo "The latest tag is: ${latestTag}"
    echo ${latestTag}
}

function getPodGitLocalLatestTag {
    latestTag=`git describe --tags`
    echo ${latestTag}
}

function getPodspecVersion {
    ###
    # Get pod version
    ###
    ret=`awk '$1 == "spec.version" {print $3}' ${podspecPath}`
    ret=${ret//\"/}
    echo ${ret}
}

function updatePodspec {
   
    ###
    # Update podspec version
    ###
    echo "> Update podspec version ..."
    sed -E -i "" "s/^(.*spec\.version.*=).*$/\1 \"${newVersion}\"/" ${podspecPath}
    [[ $? != 0 ]] && echo "--- UpdatePodspec/UpdateVersion,failed. ---" && return $?

    ###
    # PODS upload
    ###
    echo "> Pods uploading ..."
    pod trunk push ${podspecPath} --verbose --allow-warnings

    # 如果session过期，则执行
    # pod trunk register "16990471@qq.com" "ssddawei" 
    # 登陆
    if [[ $? != 0 ]] ; then
        echo "--- UpdatePodspec/UploadPods,failed. ---" 
        return -1;
    else 
        echo "--- Update podspec success. ---"
        return 0;
    fi
}

main
# getPodGitLocalLatestTag
# sed -E -i "" "s/^(.*s\.version.*=).*$/\1 \"${newVersion}\"/" ${podspecPath}
# sed -E -i "" "s/^(.*spec\.version.*=).*$/\1 \"1.0.0\"/" ${podspecPath}

